package com.weiiew.backend.utils.listener;

import com.weiiew.backend.utils.HotkeyRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 动态快捷键监听管理器（支持按配置键注册）
 */
@Slf4j
@Component
public class HotkeyListenerManager {
    private final Map<String, HotkeyBinding> activeBindings = new ConcurrentHashMap<>();
    private final GlobalKeyListener keyListener = new GlobalKeyListener();
    private final ListenerManager listenerManager;
    private final HotkeyRepository repository;

    // 依赖注入改造
    public HotkeyListenerManager(ListenerManager listenerManager, HotkeyRepository repository) {
        this.listenerManager = listenerManager;
        this.repository = repository;
    }

    /**
     * 注册热键（线程安全）
     */
    public void registerHotkey(String configKey, Runnable callback) {
        int keyCode = repository.getHotkey(configKey);
        synchronized (this) {
            if (activeBindings.isEmpty()) {
                listenerManager.registerKeyListener("hotkey_manager", keyListener);
            }
            activeBindings.put(configKey, new HotkeyBinding(keyCode, callback));
        }
    }

    /**
     * 注销单个热键
     */
    public void unregisterHotkey(String configKey) {
        synchronized (this) {
            activeBindings.remove(configKey);
            if (activeBindings.isEmpty()) {
                listenerManager.unregisterKeyListener("hotkey_manager");
            }
        }
    }

    /**
     * 批量注销页面热键
     */
    public void unregisterPageHotkeys(String pageId) {
        synchronized (this) {
            activeBindings.keySet().removeIf(key -> key.startsWith(pageId + "."));
            if (activeBindings.isEmpty()) {
                listenerManager.unregisterKeyListener("hotkey_manager");
            }
        }
    }

    // 热键绑定内部类
    @AllArgsConstructor
    private static class HotkeyBinding {
        final int keyCode;
        final Runnable callback;
    }

    // 全局监听器改造
    private class GlobalKeyListener implements NativeKeyListener {
        @Override
        public void nativeKeyPressed(NativeKeyEvent e) {
            activeBindings.values().stream()
                    .filter(binding -> binding.keyCode == e.getKeyCode())
                    .forEach(binding -> {
                        try {
                            binding.callback.run();
                        } catch (Exception ex) {
                            log.error("热键回调异常: {}", ex.getMessage());
                        }
                    });
        }

        @Override public void nativeKeyReleased(NativeKeyEvent e) {}
        @Override public void nativeKeyTyped(NativeKeyEvent e) {}
    }
}